package com.css.dzj.dzjap.sys.user.controller;

import com.css.dzj.dzjap.common.annotation.SysLog;
import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.validator.ValidatorUtils;
import com.css.dzj.dzjap.sys.user.entity.User;
import com.css.dzj.dzjap.sys.user.form.RegisterForm;
import com.css.dzj.dzjap.sys.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 用户注册
 * @author liyuan
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     *
     * @param form
     * @return
     */
    @SysLog("用户注册")
    @PostMapping("/register")
    public R register(@RequestBody RegisterForm form) {
        try {
            // 表单校验
            ValidatorUtils.validateEntity(form);
            // 根据用户名查找是否重复
            Boolean userExist = userService.isUserExist(form.getUserName());
            if (!userExist) {
                User user = new User();
                user.setUserName(form.getUserName());
                // 对用户密码进行加密
                user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
                user.setEmail(form.getEmail());
                user.setMobile(form.getMobile());
                user.setCreateTime(new Date());
                user.setDelFlag(Constant.NO_DELETE);
                // 新增用户
                userService.save(user);
                return R.ok();
            } else {
                return R.error(500,"用户名已存在");
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

}
